package com.lisa.auto.service.c3.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.lisa.auto.entity.c3.model.BrandInfo;
import com.lisa.auto.entity.c3.model.Maker;
import com.lisa.auto.entity.c3.response.BaseResponse;
import com.lisa.auto.enums.C3UrlEnum;
import com.lisa.auto.mapper.c3.MakerMapper;
import com.lisa.auto.service.c3.BrandInfoService;
import com.lisa.auto.service.c3.MakerService;
import com.lisa.auto.util.basic.BaseException;
import demo.C3ApiDemo;
import demo.request.DemoSignRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 制造商信息 服务实现类
 * </p>
 *
 * @author hxh
 * @since 2019-12-20
 */
@Service
public class MakerServiceImpl extends ServiceImpl<MakerMapper, Maker> implements MakerService {

    @Value("${c3.url}")
    private String c3url;
    @Value("${c3.appKey}")
    private String appKey;
    @Value("${c3.secretKey}")
    private String secretKey;

    @Autowired
    private BrandInfoService brandInfoService;

    @Override
    public List<Maker> queryMakersToSave() {
        try {
            String url = c3url + C3UrlEnum.MAKERSURL.getUrl();
            DemoSignRequest request = new DemoSignRequest();
            request.setAppKey(appKey);
            String requestJson = JSONObject.toJSONString(request);
            String result = C3ApiDemo.get(url, requestJson, secretKey);
            if (StringUtils.isNotBlank(result)) {
                BaseResponse<Maker> baseResponse = JSONObject.parseObject(result, BaseResponse.class);
                JSONObject jsonObject = JSONObject.parseObject(result);
                if (!baseResponse.isReturnSuccess()) {
                    throw new BaseException("获取品牌信息查询:" + baseResponse.getReturnErrMsg());
                }
                List<Maker> list = JSON.parseArray(JSON.toJSONString(jsonObject.get("list")), Maker.class);
                if (list != null) {
                    baseMapper.delete(new EntityWrapper<>());
                    for (Maker maker : list) {
                        if (StringUtils.isNotBlank(maker.getNo()))
                            baseMapper.insert(maker);
                    }
                }
                return list;
            }
            return null;
        } catch (IOException e) {
            throw new BaseException(e.getMessage());
        } catch (Exception e) {
            throw new BaseException(e.getMessage());
        }
    }

    @Override
    public void addMaker(Maker maker) {
        if (StringUtils.isEmpty(maker.getNo())) {
            throw new BaseException("制造商编码不能为空");
        }
        if (StringUtils.isEmpty(maker.getName())) {
            throw new BaseException("制造商名称不能为空");
        }
        //查询该车架号是否已存在，存在就更新，不存在就新增
        EntityWrapper<Maker> ew = new EntityWrapper<>();
        ew.eq("no", maker.getNo());
        List<Maker> makers = baseMapper.selectList(ew);
        if (makers != null && !makers.isEmpty()) {
            baseMapper.update(maker, ew);
        } else {
            baseMapper.insert(maker);
        }
    }

    @Override
    public List<Maker> getMakersList(Map<String, Object> condition) {
        EntityWrapper<Maker> ew = buildWrapper(condition);
        List<Maker> makersList = baseMapper.selectList(ew);
        return makersList;
    }

    @Override
    public Page<Maker> getMakersListPage(Page<Maker> page) {
        if (page == null) {
            throw new BaseException("参数不能为空");
        }
        EntityWrapper<Maker> ew = buildWrapper(page.getCondition());
        List<Maker> makersList = baseMapper.getMakersListPage(ew, page);
        page.setRecords(makersList);
        return page;
    }

    private EntityWrapper<Maker> buildWrapper(Map<String, Object> cd) {
        EntityWrapper<Maker> ew = new EntityWrapper<>();
        if (cd != null) {
            if (Objects.nonNull(cd.get("no")) &&
                    StringUtils.isNotBlank(cd.get("no").toString())) {
                ew.like("no", cd.get("no").toString());
            }
            if (Objects.nonNull(cd.get("name")) &&
                    StringUtils.isNotBlank(cd.get("name").toString())) {
                ew.like("name", cd.get("name").toString());
            }
            if (Objects.nonNull(cd.get("status")) &&
                    StringUtils.isNotBlank(cd.get("status").toString())) {
                ew.eq("status", cd.get("status").toString());
            }
            if (Objects.nonNull(cd.get("startDate")) && StringUtils.isNotEmpty((String) cd.get("startDate"))) {
                ew.ge("gmt_create", cd.get("startDate").toString());
            }
            if (Objects.nonNull(cd.get("endDate")) && StringUtils.isNotEmpty((String) cd.get("endDate"))) {
                ew.le("gmt_create", cd.get("endDate").toString());
            }
        }
        ew.orderBy("gmt_create", Boolean.FALSE);
        return ew;
    }

    @Override
    public void deleteById(Long id) {
        baseMapper.deleteById(id);
    }

    @Override
    public void forbiddenByIds(String id) {
        if (StringUtils.isEmpty(id)) throw new BaseException("参数为空");
        String[] ids = id.split(",");
        EntityWrapper<Maker> ew = new EntityWrapper<>();
        ew.in("id", ids);
        List<Maker> makers = baseMapper.selectList(ew);
        if (makers == null || makers.size() < 1) throw new BaseException("未查询到对应制造商信息");
        for (Maker maker : makers) {
            if ("50".equals(maker.getStatus())) throw new BaseException("存在已删除制造商");
            if ("40".equals(maker.getStatus())) throw new BaseException("存在已禁用制造商");
        }
        Maker info = new Maker();
        info.setStatus("40");
        info.setGmtModified(new Date());
        baseMapper.update(info, ew);
    }

    @Override
    public void enableByIds(String id) {
        if (StringUtils.isEmpty(id)) throw new BaseException("参数为空");
        String[] ids = id.split(",");
        EntityWrapper<Maker> ew = new EntityWrapper<>();
        ew.in("id", ids);
        List<Maker> makers = baseMapper.selectList(ew);
        if (makers == null || makers.size() < 1) throw new BaseException("未查询到对应制造商信息");
        for (Maker maker : makers) {
            if ("50".equals(maker.getStatus())) throw new BaseException("存在已删除制造商");
            if ("10".equals(maker.getStatus())) throw new BaseException("存在已启用制造商");
        }
        Maker info = new Maker();
        info.setStatus("10");
        info.setGmtModified(new Date());
        baseMapper.update(info, ew);
    }

    @Override
    public Page<Maker> getMakerAndBrandList(Page<Maker> page) {
        if (page == null) {
            throw new BaseException("参数不能为空");
        }
        EntityWrapper<Maker> ew = buildWrapper(page.getCondition());
        List<Maker> list = baseMapper.getMakersListPage(ew, page);
        if (list != null && !list.isEmpty()) {
            for (Maker maker : list) {
                EntityWrapper<BrandInfo> brandEW = new EntityWrapper<>();
                brandEW.eq("maker_no", maker.getNo());
                brandEW.eq("maker_name", maker.getName());
                brandEW.ne("status", "50");
                List<BrandInfo> brandInfos = brandInfoService.selectList(brandEW);
                maker.setBrandInfos(brandInfos);
            }
        }
        page.setRecords(list);
        return page;
    }
}
